package com.red.wood.dubbo.task;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.red.wood.common.springjdbc.CommonDao;
import com.red.wood.dubbo.model.Sql;
import com.red.wood.dubbo.model.SqlInfo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

@Service
public class StatisticsTask {
	
	private static final Log log = LogFactory.getLog(StatisticsTask.class);
	
	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private CommonDao dao;
	
	public void statics(){
		Connection conn = null;
		try{
			conn = jdbcTemplate.getDataSource().getConnection();
			ClassLoader classLoader = StatisticsTask.class.getClassLoader();  
			String xml = IOUtils.toString(classLoader.getResourceAsStream("sqlconfig/sqlInfo.xml"));  
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(SqlInfo.class);
			SqlInfo sqlInfo = (SqlInfo) xstream.fromXML(xml);
			List<Sql> list = sqlInfo.getSqls();
			log.info("==============汇总开始===============");
			for(Sql sql : list){
				String tableInfo = sql.getTableInfo();
				try{
					String deleteSql = sql.getDeleteSql();
					String insertSql = sql.getInsertSql();
					log.info("表名【"+tableInfo+"】汇总完成！");
					/*boolean flag = dao.execSql(conn, deleteSql);
					if(flag){
						flag = dao.execSql(conn, insertSql);
						if(flag){
							log.info("表名【"+tableInfo+"】汇总完成！");
						}else{
							log.info("表名【"+tableInfo+"】汇总出错！");
						}
					}*/
				}catch(Exception e){
					log.error("表名【"+tableInfo+"】汇总出错！");
					if(log.isErrorEnabled()){
						log.error(e.getMessage(),e);
					}
				}
			}
			log.info("===============汇总完成==================");
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					if(log.isErrorEnabled()){
						log.error(e.getMessage(),e);
					}
				}
			}
		}
	}
}
